#include "mesh.h"
#include <fstream>
#include <sstream>
#include <iostream>
#include <cstdlib>

bool loadObj(const std::string& filePath, Mesh& mesh)
{
    float x, y, z;
    std::string line;
    std::ifstream fs(filePath, std::ios::in);
    if (!fs.is_open()) return false;

    mesh.vertices.clear();
    mesh.texCoords.clear();
    mesh.normals.clear();

    std::vector<glm::vec3> vertVals;
    std::vector<glm::vec2> texVals;
    std::vector<glm::vec3> normVals;

    int index = 0;
    while (!fs.eof())
    {
        std::getline(fs, line);
        if (line.compare(0, 2, "v ")== 0)
        {
            std::stringstream ss(line.erase(0, 1));
            ss >> x;
            ss >> y;
            ss >> z;
            vertVals.push_back(glm::vec3(x, y, z));
        }
        if (line.compare(0, 2, "vt") == 0)
        {
            std::stringstream ss(line.erase(0, 2));
            ss >> x;
            ss >> y;
            texVals.push_back(glm::vec2(x, y));
        }
        if (line.compare(0, 2, "vn")== 0)
        {
            std::stringstream ss(line.erase(0, 2));
            ss >> x;
            ss >> y;
            ss >> z;
            normVals.push_back(glm::vec3(x, y, z));
        }

        if (line.compare(0, 2, "f ") == 0)
        {
            std::string oneCorner;
            std::string v, t, n;
            std::stringstream ss(line.erase(0, 2));
            for (int i = 0; i < 3; ++i)
            {
                std::getline(ss, oneCorner, ' ');
                std::stringstream oneCornerSS(oneCorner);

                std::getline(oneCornerSS, v, '/');
                std::getline(oneCornerSS, t, '/');
                std::getline(oneCornerSS, n, '/');
                int vertRef = (std::stoi(v) - 1);
                int tcRef = (std::stoi(t) - 1);
                int normRef = (std::stoi(n) - 1);

                mesh.vertices.push_back(vertVals[vertRef]);
                mesh.texCoords.push_back(texVals[tcRef]);
                mesh.normals.push_back(normVals[normRef]);

                mesh.indices.push_back(index);
                index += 1;
            }
        }
    }
    return true;
}
